<?php
namespace Cmf\Controllers;

use Cmf\Models\User;
use Cmf\Forms\UserForm;
use Phalcon\Http\Response;

/**
 * 用户管理控制器
 */
class UserController extends BaseController
{
	public function indexAction()
	{
		$currentPage = $this->request->getQuery('page','int');

		$list = User::find(array(
			'order'   => 'id DESC',
			'columns' => 'id,account,name,email',
		));

		$paginator = new \Phalcon\Paginator\Adapter\Model(
			array(
				'data'  => $list,
				'limit' => 15,
				'page'  => $currentPage,
			)
		);

		$page = $paginator->getPaginate();
		$this->view->page = $page;
	}

	public function newAction()
	{
		$this->view->form = new UserForm();;
	}

	public function createAction()
	{
		if($this->request->isPost()) {
			$User = new User();
			$form = new UserForm();

			if($form->isValid($this->request->getPost()) === false) {
				foreach($form->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(['controller' => 'user','action' => 'new']);
			}

			if(!$User->create($this->request->getPost())) {
				foreach($User->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward(array('controller' => 'user','action' => 'new'));
			}
			$this->flash->success('新增用户成功');

			return $this->response->redirect('user/index');
		}
		$this->response->redirect('error/show404');
	}

	public function editAction()
	{
		$user = User::findFirstById($this->request->getQuery('id','int'));
		$form = new UserForm($user,'edit');
		$this->view->form = $form;
	}

	public function updateAction()
	{
		if($this->request->isPost()) {
			$user = new User();
			$form = new UserForm();

			if($form->isValid($this->request->getPost()) === false) {
				foreach($form->getMessages() as $key => $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward('user/edit');
			}

			if(!$user->save($this->request->getPost())) {
				foreach($user->getMessages() as $message) {
					$this->flash->error($message);
				}

				return $this->dispatcher->forward('user/edit');
			}

			$this->flash->success('编辑用户成功');

			return $this->response->redirect('user/index');
		}
	}

	//删除用户操作
	public function deleteAction()
	{
		$this->view->disable();

		$user = User::findFirstById($this->request->getPost('id'));
		$response = new Response();

		if(!$user) {
			$response->setContent(json_encode(['message' => '用户不存在']));

			return $response;
		}

		if(!$user->delete()) {
			foreach($user->getMessage() as $message) {
				$this->flash->error($message);
			}
			$response->setContent(json_encode(['message' => '用户删除失败']));

			return $response;
		}

		$response->setContent(json_encode(['message' => '用户删除成功','id' => $this->request->getPost('id')]));

		return $response;
	}
}
